package com.lib76.buildCode.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.lib76.buildCode.model.DbConfig;
import com.lib76.buildCode.model.PageConfig;
import com.lib76.buildCode.model.PageEntity;
import com.lib76.buildCode.model.PageEntityField;
import com.lib76.buildCode.model.Project;
import com.lib76.buildCode.model.TableEntity;
import com.lib76.buildCode.model.TableFieldEntity;

/**
 * 项目XML配置文件生成解析服务
 * @author 张浩
 * @version 0.0.3
 *
 */
public class ProjectXmlServer {

	public static Project parseXml(File file){
		try{
	        SAXReader saxReader = new SAXReader();
	        Document document = saxReader.read(file);
	        //获取根节点对象  
            Element rootElement = document.getRootElement();
            Project project = new Project();
            project.setProjectCode(rootElement.attributeValue("code"));
            project.setProjectName(rootElement.attributeValue("name"));
            project.setProjectPackage(rootElement.attributeValue("package"));
            project.setProjectType(rootElement.attributeValue("type"));
            project.setVersion(rootElement.attributeValue("version"));
            
            Element dbConfigElement = rootElement.element("dbConfig");
            if(dbConfigElement != null){
            	DbConfig config = new DbConfig();
            	config.setIp(dbConfigElement.attributeValue("ip"));
            	config.setPort(Integer.valueOf(dbConfigElement.attributeValue("port")));
            	config.setUserName(dbConfigElement.attributeValue("userName"));
            	config.setUserPwd(dbConfigElement.attributeValue("userPwd"));
            	//获取子节点  
            	Iterator<Element> tableIterator = dbConfigElement.elementIterator("table");
                if(tableIterator != null){
                	 while(tableIterator.hasNext()){
                		 Element tableElement = tableIterator.next(); 
                		 TableEntity table = new TableEntity();
                		 table.setTableName(tableElement.attributeValue("tableName"));
                		 table.setTableChinaName(tableElement.attributeValue("tableChinaName"));
                		 table.setClassName(tableElement.attributeValue("className"));
                		 String isExist = tableElement.attributeValue("isExist");
                		 if(StringUtils.isNotBlank(isExist)){table.setIsExist(Boolean.valueOf(isExist));}
                		 else{table.setIsExist(false);}
                		 Iterator<Element> fieldIterator = tableElement.elementIterator("field");
                		 if(fieldIterator != null){
                        	 while(fieldIterator.hasNext()){
                        		 Element fieldElement = fieldIterator.next(); 
                        		 TableFieldEntity field = new TableFieldEntity();
                        		 field.setCode(fieldElement.attributeValue("code"));
                        		 field.setName(fieldElement.attributeValue("name"));
                        		 field.setType(fieldElement.attributeValue("type"));
                        		 String length = fieldElement.attributeValue("length");
                        		 if(StringUtils.isNotBlank(length)){field.setLength(Long.valueOf(length));}
                        		 String isKey = fieldElement.attributeValue("isKey");
                        		 if(StringUtils.isNotBlank(isKey)){field.setIsKey(Boolean.valueOf(isKey));}
                        		 String isNullable = fieldElement.attributeValue("isNullable");
                        		 if(StringUtils.isNotBlank(isNullable)){field.setIsNullable(Boolean.valueOf(isNullable));}
                        		 table.getFields().put(field.getCode(), field);
                        	 }
                		 }
                		 config.getTables().put(table.getTableName(), table);
                	 }
                }
                project.setDbConfig(config);
            }
            Element pageConfigElement = rootElement.element("pageConfig");
            if(pageConfigElement != null){
            	PageConfig pageConfig = new PageConfig();
            	pageConfig.setTemplateType(pageConfigElement.attributeValue("templateType"));
            	//对象的页面配置
            	Iterator<Element> pageEntityIterator = pageConfigElement.elementIterator("pageEntity");
                if(pageEntityIterator != null){
                	 while(pageEntityIterator.hasNext()){
                		 Element pageEntityElement = pageEntityIterator.next(); 
                		 PageEntity pageEntity = new PageEntity();
                		 pageEntity.setEntityClassName(pageEntityElement.attributeValue("className"));
                		 pageEntity.setEntityChinaName(pageEntityElement.attributeValue("entityChinaName"));
                		 pageEntity.setMenuName(pageEntityElement.attributeValue("emnuName"));
                		 pageEntity.setToEditModal(pageEntityElement.attributeValue("toEditModal"));
                		 
                		 Iterator<Element> fieldIterator = pageEntityElement.elementIterator("field");
                		 if(fieldIterator != null){
                        	 while(fieldIterator.hasNext()){
                        		 Element pageEntityFieldElement = fieldIterator.next(); 
                        		 PageEntityField pageEntityField = new PageEntityField();
                        		 pageEntityField.setCode(pageEntityFieldElement.attributeValue("code"));
                        		 pageEntityField.setName(pageEntityFieldElement.attributeValue("name"));
                        		 pageEntityField.setInputType(pageEntityFieldElement.attributeValue("inputType"));
                        		 pageEntityField.setIsDisplayForm(Boolean.valueOf(pageEntityFieldElement.attributeValue("isDisplayForm")));
                        		 pageEntityField.setIsDisplayTable(Boolean.valueOf(pageEntityFieldElement.attributeValue("isDisplayTable")));
                        		 pageEntity.getFields().put(pageEntityField.getCode(), pageEntityField);
                        	 }
                		 }
                		 pageConfig.getEntitys().put(pageEntity.getEntityClassName(), pageEntity);
                	 }
                }
                project.setPageConfig(pageConfig);
            	
            }
	        return project;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static boolean buildXml(Project project,String path){
		XMLWriter xmlWriter = null;
		try{
			Document document = DocumentHelper.createDocument();
			//添加节点信息  
            Element rootElement = document.addElement("project");
            rootElement.addAttribute("code",project.getProjectCode());
            rootElement.addAttribute("name",project.getProjectName());
            rootElement.addAttribute("package",project.getProjectPackage());
            rootElement.addAttribute("type",project.getProjectType());
            rootElement.addAttribute("version",project.getVersion());
            if(project.getDbConfig() != null){
            	DbConfig config = project.getDbConfig();
            	Element dbConfigElement = rootElement.addElement("dbConfig");
            	dbConfigElement.addAttribute("ip",config.getIp());
            	dbConfigElement.addAttribute("port",config.getPort().toString());
            	dbConfigElement.addAttribute("userName",config.getUserName());
            	dbConfigElement.addAttribute("userPwd",config.getUserPwd());
            	for(TableEntity table:config.getTables().values()){
            		Element tableElement = dbConfigElement.addElement("table");
            		tableElement.addAttribute("tableName", table.getTableName());
            		tableElement.addAttribute("tableChinaName",table.getTableChinaName());
            		tableElement.addAttribute("className",table.getClassName());
            		tableElement.addAttribute("isExist",table.getIsExist().toString());
            		for(TableFieldEntity field:table.getFields().values()){
            			Element fieldElement = tableElement.addElement("field");
            			fieldElement.addAttribute("code",field.getCode());
            			fieldElement.addAttribute("name",field.getName());
            			fieldElement.addAttribute("type",field.getType());
            			if(field.getLength() != null){
            				fieldElement.addAttribute("length",field.getLength().toString());
            			}
            			fieldElement.addAttribute("isKey",field.getIsKey().toString());
            			fieldElement.addAttribute("isNullable",field.getIsNullable().toString());
            		}
            	}
            }
            if(project.getPageConfig() != null){
            	PageConfig pageConfig = project.getPageConfig();
            	Element pageConfigElement = rootElement.addElement("pageConfig");
            	pageConfigElement.addAttribute("templateType",pageConfig.getTemplateType());
            	for(PageEntity pageEntity:pageConfig.getEntitys().values()){
            		Element pageEntityElement = pageConfigElement.addElement("pageEntity");
            		pageEntityElement.addAttribute("className", pageEntity.getEntityClassName());
            		pageEntityElement.addAttribute("entityChinaName",pageEntity.getEntityChinaName());
            		pageEntityElement.addAttribute("emnuName",pageEntity.getMenuName());
            		pageEntityElement.addAttribute("toEditModal",pageEntity.getToEditModal());
            		for(PageEntityField field:pageEntity.getFields().values()){
            			Element pageEntityFieldElement = pageEntityElement.addElement("field");
            			pageEntityFieldElement.addAttribute("code",field.getCode());
            			pageEntityFieldElement.addAttribute("name",field.getName());
            			pageEntityFieldElement.addAttribute("inputType",field.getInputType());
            			pageEntityFieldElement.addAttribute("isDisplayTable",field.getIsDisplayTable().toString());
            			pageEntityFieldElement.addAttribute("isDisplayForm",field.getIsDisplayForm().toString());
            		}
            	}
            }
            File file = new File(path);
            if(!file.exists()){file.mkdirs();}
            Writer fileWriter = new FileWriter(path+"/"+project.getProjectCode()+".xml");
            xmlWriter = new XMLWriter(fileWriter);  
            xmlWriter.write(document);  
            xmlWriter.flush();
            return true;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(xmlWriter != null){
				try {
					xmlWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
}
